<template>
  <div class="publish">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <el-breadcrumb separator-class="el-icon-arrow-right">
          <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item>文章发布</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <el-form
        v-loading="isloading"
        :model="article"
        :rules="rules"
        ref="publish"
        label-width="80px"
        class="demo-ruleForm"
      >
        <el-form-item label="标题：" prop="title">
          <el-input v-model="article.title" class="inp1"></el-input>
        </el-form-item>
        <!-- <el-taptap v-model="article.content" ></el-taptap> -->

        <el-form-item label="内容：" prop="content">
          <el-tiptap
            v-model="article.content"
            :extensions="extensions"
            placeholder="请输入内容"
            width="100%"
            :height="350"
          ></el-tiptap>
        </el-form-item>

        <el-form-item label="封面：" prop="cover">
          <el-radio-group v-model="article.cover.type">
            <el-radio :label="1">单图</el-radio>
            <el-radio :label="3">三图</el-radio>
            <el-radio :label="0">无图</el-radio>
            <el-radio :label="-1">自动</el-radio>
          </el-radio-group>

          <template v-if="article.cover.type > 0">
            <ul class="select_box">
              <li
              
              v-for="(cover, i) in article.cover.type"
                  :key="cover"
              >
                <upload-cover
                 v-model="article.cover.images[i]"
                 
                ></upload-cover>
                 <!-- @share-image="shareImageArr(i,$event)" -->
              </li>
            </ul>
          </template>
        </el-form-item>

        <el-form-item label="频道：" prop="channel_id">
          <el-select v-model="article.channel_id" placeholder="请选择内容频道">
            <el-option
              v-for="item in channelsList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button
            :disabled="isloading"
            type="primary"
            @click="onPublish(false)"
            >{{ articleId ? "修改" : "发布" }}</el-button
          >
          <el-button :disabled="isloading" @click="onPublish(true)"
            >存入草稿</el-button
          >
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { getArticleChannels } from "@/request/api.js";
import { addArticle } from "@/request/api.js";
import { getArticleDetial } from "@/request/api.js";
import { updateArticle } from "@/request/api.js";
import { uploadImage } from "@/request/api.js";
import UploadCover from "./components/UploadCover.vue";

import {
  ElementTiptap,
  Doc,
  Text,
  Paragraph,
  Heading,
  Bold,
  Underline,
  Italic,
  Image,
  Strike,
  ListItem,
  BulletList,
  OrderedList,
  TodoItem,
  TodoList,
  HorizontalRule,
  Fullscreen,
  Preview,
  CodeBlock,
  TextColor,
} from "element-tiptap";
import "element-tiptap/lib/index.css";
export default {
  name: "Publish",
  components: {
    "el-tiptap": ElementTiptap,
    UploadCover,
  },
  data() {
    return {
      // extensions:"", // 富文本编译器
      articleId: 0,

      isloading: false,
      //内容
      article: {
        title: "", // 标题
        content: "", // 内容
        cover: {
          type: 0, // -1自动 0无图 1一张 3三张
          images: [],
        }, // 封面
        channel_id: null,
      },
      channelsList: [],
      extensions: [
        new Doc(),
        new Text(),
        new Paragraph(),
        new Heading({ level: 3 }),
        new Bold({ bubble: true }), // 在气泡菜单中渲染菜单按钮
        new Image({
          uploadRequest(file) {
            let fd = new FormData();
            fd.append("image", file);

            return uploadImage(fd).then((res) => {
              return res.data.data.url;
            });
          },
        }),
        new Underline(), // 下划线
        new Italic(), // 斜体
        new Strike(), // 删除线
        new HorizontalRule(), // 华丽的分割线
        new ListItem(),
        new BulletList(), // 无序列表
        new OrderedList(), // 有序列表
        new TodoItem(),
        new TodoList(),
        new Fullscreen(),
        new Preview(),
        new CodeBlock(),
        new TextColor(),
      ],
      rules: {
        title: [
          {
            required: true,
            message: "请输入活动名称",
            trigger: "change",
            min: 1,
          },
        ],
        content: [
          {
            required: true,
            message: "请输入内容",
            trigger: "change",
            min: 1,
          },
        ],

        channel_id: [
          {
            validator: (rule, value, callback) => {
              if (value) {
                callback();
              } else {
                callback(new Error("请选择频道"));
              }
            },
            required: true,
            trigger: "change",
          },
        ],
      },
    };
  },
  created() {
    this.articleId = this.$route.query.id;
    this.initChannels();

    if (this.articleId) {
      this.initArticleDetail();
    }
  },
  methods: {
    async initChannels() {
      const { data: res } = await getArticleChannels();
      this.channelsList = res.data.channels;
    },

    onPublish(draft = false) {
      this.$refs["publish"].validate((valid, err) => {
        if (!valid) {
          console.log(err);
          return;
        } else {
          this.isloading = true;
          if (this.articleId) {
            // if(this.article.cover.type != this.article.cover.images.length 
            // && this.article.cover.type > 0
            // ){
             
            //   let arr = this.article.cover.images
            //   this.article.cover.images = []
            //   for(let i = 0 ; i < this.article.cover.type ; i++){
            //     this.article.cover.images.push(arr[i])
            //   }
            
            // }else if(this.article.cover.type <= 0){
            //   this.article.cover.images = []
            //   console.log("66666")
            // }

            // 修改操作
            this.getUpdata(draft)
          } else {

            // 发布操作
            addArticle(this.article, draft)
              .then(() => {
                this.$message({
                  message: `${draft ? "存入草稿" : "发布"}成功`,
                  type: "success",
                });
                this.isloading = false;
                this.$router.push("/article");
              })
              .catch(() => {
                this.$message.error(`${draft ? "存入草稿" : "发布"}失败`);
                this.isloading = false;
              });
          }
        }
      });
    },

    // 获取文章的详情
    initArticleDetail() {
      this.isloading = true;
      getArticleDetial(this.articleId).then((res) => {
        console.log("文章详情", res.data);
        this.article = res.data.data;

        // this.article.content = this.article.content
        //   .replace(/<[^>]+>/g, "")
        //   .trim();

        this.isloading = false;
      });
    },

    // 修改函数
    getUpdata(draft){
      updateArticle(this.articleId, this.article, draft)
              .then(() => {
                this.$message({
                  message: `${draft ? "存入草稿" : "修改"}成功`,
                  type: "success",
                });
                this.isloading = false;
                this.$router.push("/article");
              })
              .catch(() => {
                this.$message.error(`${draft ? "存入草稿" : "修改"}失败`);
                this.isloading = false;
              });
    }


    // shareImageArr(index,val){
    //   console.log(index,val)
    //   this.article.cover.images[index] = val
    // }
  },
};
</script>

<style lang="less" scoped>
.inp1 {
  width: 50%;
}
.select_box{
  display: flex;
  flex-wrap: wrap;
  li{
    margin-right: 20px;
    margin-bottom:13px;
  }
  
  
}
</style>

